﻿using System.Windows.Controls;
using System.Windows.Controls.Primitives;

namespace Flux.Editor.Extensions
{
	public static class TreeViewExtensions
	{
		private static TreeViewItem GetContainerFromItem(this ItemsControl parent, object item)
		{
			var found = parent.ItemContainerGenerator.ContainerFromItem(item);
			if (found == null)
			{
				for (var i = 0; i < parent.Items.Count; i++)
				{
					var childContainer = parent.ItemContainerGenerator.ContainerFromIndex(i) as ItemsControl;
					TreeViewItem childFound = null;
					if (childContainer != null && childContainer.ItemContainerGenerator.Status != GeneratorStatus.ContainersGenerated)
					{
						childContainer.ItemContainerGenerator.StatusChanged += (o, e) =>
						{
							childFound = GetContainerFromItem(childContainer, item);
						};
					}
					else
					{
						childFound = GetContainerFromItem(childContainer, item);
					}
					if (childFound != null) return childFound;
				}
			}
			return found as TreeViewItem;
		}

		public static void SelectTreeViewItem(this TreeView treeView, object item)
		{
			try
			{
				var treeViewItem = treeView.GetContainerFromItem(item);
				treeViewItem.Focus();
				treeViewItem.IsSelected = true;
				var selectMethod = typeof(TreeViewItem).GetMethod("Select", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance);
				selectMethod.Invoke(treeViewItem, new object[] {true});
			}
			catch {}
		}

	}
}